package com.lktx.sso.controller;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.oauth2.SaOAuth2Manager;
import cn.dev33.satoken.oauth2.annotation.SaCheckAccessToken;
import cn.dev33.satoken.oauth2.template.SaOAuth2Util;
import cn.dev33.satoken.util.SaResult;
import cn.hserver.core.ioc.annotation.Autowired;
import cn.hserver.core.server.util.JsonResult;
import cn.hserver.plugin.web.annotation.Controller;
import cn.hserver.plugin.web.annotation.POST;
import cn.hserver.plugin.web.annotation.RequestMapping;
import cn.hutool.json.JSONUtil;
import com.lktx.sso.admin.mapper.SsoUserMapper;
import com.lktx.sso.service.OpenApiService;

import java.util.Map;

@Controller
public class OpenApiController {

    @Autowired
    private OpenApiService openApiService;

    @Autowired
    private SsoUserMapper ssoUserMapper;



    // 获取 userinfo 信息：昵称、头像、性别等等
    @POST("/{appId}/oauth2/userinfo")
    public SaResult userinfo(String appId) {
        System.out.println("userinfo:" + appId);
        // 获取 Access-Token 对应的账号id
        String accessToken = SaOAuth2Manager.getDataResolver().readAccessToken(SaHolder.getRequest());
        Object loginId = SaOAuth2Util.getLoginIdByAccessToken(accessToken);
        System.out.println("-------- 此Access-Token对应的账号id: " + loginId);
        // 校验 Access-Token 是否具有权限: userinfo
        SaOAuth2Util.checkAccessTokenScope(accessToken, "userinfo");
        // 模拟账号信息 （真实环境需要查询数据库获取信息）
        Map<String, Object> userInfo = ssoUserMapper.getLoginUserInfo(loginId.toString());
        System.out.println(JSONUtil.toJsonStr(userInfo));
        return SaResult.data(userInfo);
    }


    // 获取 userinfo 信息：昵称、头像、性别等等
    @SaCheckAccessToken(scope = {"center"})
    @POST("/{appId}/oauth2/center")
    public SaResult center(String appId) {
        return SaResult.data(openApiService.appCenter());
    }

}
